from werkzeug.exceptions import HTTPException


class APIException(HTTPException):
    code = 500  # http状态码
    message = "opps!"   # 状态描述信息
    status_code = 9999  # 程序状态

    def __init__(self, message=None, code=None, status_code=None):
        if message:
            self.message = message
        if code:
            self.code = code
        if status_code:
            self.status_code = status_code
        # 包含一下父类init函数的处理
        super(APIException, self).__init__()

    def get_body(
            self,
            environ=None,
            scope=None,
    ) -> str:
        body = dict(
            # 定义了一个字典
            message=self.message,
            status_code=self.status_code
        )
        import json
        # 把字典转换成json格式并返回
        content = json.dumps(body)
        return content

    def get_headers(
            self,
            environ=None,
            scope=None,
    ):
        return [('content-Type', 'application/json')]


class APIAuthorizedException(APIException):
    message = "API授权认证失败"
    status_code = 10002
    code = 401


class FormValidateException(APIException):
    message = "表单验证失败"
    status_code = 10003


class TokenFailException(APIException):
    message = "token不合法，验证失败"
    status_code = 10005
    code = 401
